package com.ojoin.trade.t0loan_core.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.web.shiro.Principal;

/**
 * 登录拦截器
 * 
 * @author huanggc
 * 
 */

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = LoggerFactory
			.getLogger(LoginInterceptor.class);


	private static final String[] OPERATE_IGNORE_URI = {"/operate/login","/system/token" };

	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (!(handler instanceof HandlerMethod))
			return true;
		
		boolean flag = false;
		String url = request.getRequestURI();
        String[] urls = url.split("/"); 

		if (url.startsWith("/sys/")||url.startsWith("/operate/") ||(urls.length>2 && urls[2].equals("operate"))) {
			for (String s : OPERATE_IGNORE_URI) {
				if (url.contains(s)) {
					flag = true;
					break;
				}
			}	
			if (!flag) {
				//保理员用户
				Principal principal = CommonUtils.getPrincipal();
				Subject subject = CommonUtils.getSubject();
				//登录九盈后没有退出，又访问保理系统
				 if(null!=principal&&!principal.getLoginType().equals(IConstDef.loginType_Factor)){
					 subject.logout();
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}


    /**
     * 上一次请求的地址
     * 1、先从request.parameter中查找BackURL
     * 2、获取header中的 referer
     *
     * @param request
     * @return
     */
    private String extractBackURL(HttpServletRequest request) {
        String url = request.getParameter(Constants.BACK_URL);

        if (StringUtils.isEmpty(url)) {
            url = request.getHeader("Referer");
        }

        if(!StringUtils.isEmpty(url) && (url.startsWith("http://") || url.startsWith("https://"))) {
            return url;
        }

        if (!StringUtils.isEmpty(url) && url.startsWith(request.getContextPath())) {
            url = getBasePath(request) + url;
        }
        return url;
    }

    private String getBasePath(HttpServletRequest req) {
        StringBuffer baseUrl = new StringBuffer();
        String scheme = req.getScheme();
        int port = req.getServerPort();

        baseUrl.append(scheme);        // http, https
        baseUrl.append("://");
        baseUrl.append(req.getServerName());
        if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
            baseUrl.append(':');
            baseUrl.append(req.getServerPort());
        }
        return baseUrl.toString();
    }
    
	
}
